package Code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Code56 {
    public static int[][] merge(int[][] intervals) {
        if(intervals == null || intervals.length == 0) return new int[0][0];
//        Arrays.sort(intervals, Comparator.comparingInt(a->a[0]));
        Arrays.sort(intervals, (a,b)->(a[0]- b[0]));
        List<int[]> merged = new ArrayList<>();

        int[] pre = intervals[0];
        for(int i = 1; i< intervals.length; i++){
            int[] cur = intervals[i];
            if(pre[1] >= cur[0]){
                pre[1] = Math.max(pre[1], cur[1]);
            }else{
                merged.add(pre);
                pre = cur;
            }
        }
        merged.add(pre);
        return merged.toArray(new int[merged.size()][]);
    }
    public static void main(String[] args) {
        int[][] intervals = {{1,4},{4,5}};
        System.out.println(Arrays.stream(merge(intervals))
                .map(interval -> Arrays.stream(interval).boxed().toList())
                .collect(Collectors.toList()));
    }
}
